package com.lepu.app.fun.my;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.app.application.MyApplication;
import com.app.config.UserConfig;
import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.SdLocal;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.utils.CallBack;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.MyDialog;
import com.eyzhs.app.R;
import com.lepu.app.fun.chat.business.AppCommonService;
import com.lepu.app.fun.grow.fragment.FragmentGrow;
import com.lepu.app.main.activity.MainTabActivity;
import com.lepu.app.usercenter.ModifyPwdActivity;
import com.lepu.app.usercenter.ModifyPwdQuestionActivity;
import com.lepu.app.usercenter.AboutMainActivity;
import com.lepu.app.usercenter.UserBondActivity;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class SettingActivity extends BaseFragmentActivity implements
        OnTopbarNewLeftLayoutListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_setting_activity);

        init();
    }

    @Override
    public void onResume() {
        super.onResume();

        updateLoginState();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 添加页面动画，需要重写这个方法，
     */
    @Override
    public void onBackPressed() {
        finish(true);
    }

    /**
     * 初始化方法
     */
    private void init() {
        // topbar
        CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
        topbar.setTopbarTitle("设置");
        topbar.setonTopbarNewLeftLayoutListener(this);

        RelativeLayout pwdQuestionLayout = (RelativeLayout) findViewById(R.id.pwdQuestionLayout);
        RelativeLayout modifyPwdLayout = (RelativeLayout) findViewById(R.id.modifyPwdLayout);
        RelativeLayout aboutLayout = (RelativeLayout) findViewById(R.id.aboutLayout);

        RelativeLayout cacheLayout = (RelativeLayout) findViewById(R.id.cacheLayout);
        Button loginStateButton = (Button) findViewById(R.id.loginStateButton);

        pwdQuestionLayout.setOnClickListener(mOnClickListener);
        modifyPwdLayout.setOnClickListener(mOnClickListener);
        aboutLayout.setOnClickListener(mOnClickListener);

        cacheLayout.setOnClickListener(mOnClickListener);
        loginStateButton.setOnClickListener(mOnClickListener);

        //有的手机点击设置闪退，
        updateCache();
    }

    private void updateCache() {
//		TextView cacheValueTextView = (TextView) findViewById(R.id.cacheValueTextView);
//		// String filePath = SdLocal.getCacheImageFolder(this);
//
//		String filePath = SdLocal.getTempFolder(this);
//		String fileSize = FileSizeUtil.getAutoFileOrFilesSize(filePath);
//		if (fileSize.equals("0B")) {
//			cacheValueTextView.setText("0M");
//		} else {
//			cacheValueTextView.setText(fileSize);
//		}
    }

    private void updateLoginState() {
        TextView pwdQuestionStateTextView = (TextView) findViewById(R.id.pwdQuestionStateTextView);
        Button loginStateButton = (Button) findViewById(R.id.loginStateButton);

        if (MyApplication.getInstance().checkIsLogin()) {
            loginStateButton.setTag(0);
            loginStateButton.setText("退出登录");

            LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
            if (!TextUtils.isEmpty(loginInfo.HasSecurityQuestion) && loginInfo.HasSecurityQuestion.equals("1")) {
            	pwdQuestionStateTextView.setText("修改");
            } else {
                pwdQuestionStateTextView.setText("未设置");
            }
        } else {
            loginStateButton.setTag(1);
            loginStateButton.setText("去登录");

            pwdQuestionStateTextView.setText("");
        }
    }

    private static final int MSG_CLEAN_CACHE = 10;

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case MSG_CLEAN_CACHE:

                    hideProgressDialog();
                    updateCache();

                    UIHelper.showToast(SettingActivity.this, "清理缓存成功");

                    break;

                default:
                    break;
            }
        }
    };
    
    private void goBondPhone(String message)
    {
    	new MyDialog(SettingActivity.this)
        .setMessage(message)
        .setNegativeButton(R.string.app_cancel,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                    }
                })
        .setPositiveButton(R.string.my_modify_pwd_ok_bond_button,
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                    	Intent intent = new Intent(SettingActivity.this, UserBondActivity.class);
            			startActivity(intent, true);
                    }
                }).create(null).show();
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent intent = null;
            switch (v.getId()) {
                case R.id.pwdQuestionLayout:

                    boolean flag = MainTabActivity.jumpLogin(SettingActivity.this);

                    if (!flag) {
                        LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
                        if (!TextUtils.isEmpty(loginInfo.HasSecurityQuestion) && loginInfo.HasSecurityQuestion.equals("1")) {
                        	if(LoginUtil.checkIsBond()){
                        		intent = new Intent(SettingActivity.this,
                                        ModifyPwdQuestionActivity.class);
                                startActivity(intent, true);
                            }else{
                            	String message = "您需要先绑定手机号才能修改密保问题，是否前去绑定？";
                            	goBondPhone(message);
                            }
                        } else {
                        	 intent = new Intent(SettingActivity.this,
                                     ModifyPwdQuestionActivity.class);
                             startActivity(intent, true);
                        }
                    }

                    break;
                case R.id.modifyPwdLayout:

                    boolean flag2 = MainTabActivity.jumpLogin(SettingActivity.this);
                    if (!flag2) {
                        if(LoginUtil.checkIsBond()){
                        	intent = new Intent(SettingActivity.this,
                                    ModifyPwdActivity.class);
                            startActivity(intent, true);
                        }else{
                        	String message = "您需要先绑定手机号才能设置密码，是否前去绑定？";
                        	goBondPhone(message);
                        }
                    }

                    break;
                case R.id.cacheLayout:
                    // clean cache
                    new MyDialog(SettingActivity.this)
                            .setMessage("您确定清理缓存吗?")
                            .setNegativeButton(R.string.app_cancel,
                                    new View.OnClickListener() {

                                        @Override
                                        public void onClick(View v) {

                                        }
                                    })
                            .setPositiveButton(R.string.app_ok,
                                    new View.OnClickListener() {

                                        @Override
                                        public void onClick(View v) {

                                            showProgressDialog();
                                            Utils.cleanAllCache(SettingActivity.this,
                                                     new CallBack() {
                                                        public void callBackSuccess(
                                                                Object obj) {
                                                            mHandler.sendEmptyMessage(MSG_CLEAN_CACHE);
                                                        }
                                                    });
                                        }
                                    }).create(null).show();
                    break;
                case R.id.aboutLayout:
                    intent = new Intent(SettingActivity.this,
                            AboutMainActivity.class);
                    startActivity(intent, true);
                    break;
                case R.id.loginStateButton:

                    if (FragmentGrow.getInstance() != null) {
                        if (FragmentGrow.getInstance().mIsUpdate) {
                            UIHelper.showToast(SettingActivity.this, "数据正在同步中，请稍后再试");
                            return;
                        }
                    }

                    int tag = (Integer) v.getTag();
                    if (tag == 0) {
                        new MyDialog(SettingActivity.this)
                                .setMessage("确定退出当前账户?")
                                .setNegativeButton(R.string.app_cancel,
                                        new View.OnClickListener() {

                                            @Override
                                            public void onClick(View v) {

                                            }
                                        })
                                .setPositiveButton(R.string.app_quit,
                                        new View.OnClickListener() {

                                            @Override
                                            public void onClick(View v) {
                                                // log out
                                                UserConfig
                                                        .clearLoginConfig(SettingActivity.this);
                                                MyApplication.getInstance()
                                                        .setLoginInfo(null);

                                                MainTabActivity instance = MainTabActivity
                                                        .getInstance();
                                                if (instance != null) {
                                                    instance.mHandler
                                                            .sendEmptyMessage(MainTabActivity.MSG_LOGOUT_UPDATE);
                                                }

                                                updateLoginState();

                                                finish(true);
                                                //set chatsession_message
                                                ObserverManager.getInstance().notify(ObserverConst.NOTIFY_ZXRECORDER_CHANGE, null, null);
                                                AppCommonService.getInstance().logoutXGXMPP();

                                            }
                                        }).create(null).show();

                    } else {
                        // log in
                        MainTabActivity.jumpLogin(SettingActivity.this);

                        // test
                        // String value = testLoginInfo();
                        // UserConfig.setConfig(SettingActivity.this,
                        // Const.CONFIG_APP_LOGIN_INFO, value);
                        // UIHelper.showToast(SettingActivity.this, "登录成功");
                        //
                        // LoginInfo loginInfo = LoginInfo.parseLoginInfo(value);
                        // MyApplication.getInstance().setLoginInfo(loginInfo);
                        //
                        // MainTabActivity instance = MainTabActivity.getInstance();
                        // if (instance != null) {
                        // instance.mHandler
                        // .sendEmptyMessage(MainTabActivity.MSG_LOGIN_UPDATE);
                        // }
                        //
                        // updateLoginState();
                    }
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    public void onTopbarLeftLayoutSelected() {
        finish(true);
    }

}
